package com.niubi.yygh.hosp.receiver;

import com.niubi.yygh.hosp.service.ScheduleService;
import com.niubi.yygh.model.hosp.Schedule;
import com.niubi.yygh.rabbit.RabbitService;
import com.niubi.yygh.rabbit.constant.MqConst;
import com.niubi.yygh.vo.msm.MsmVo;
import com.niubi.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class HospitalReceiver {
  @Autowired
  ScheduleService scheduleService;

  @Autowired
  RabbitService rabbitService;

  @RabbitListener(bindings = @QueueBinding(
          value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
          exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
          key = {MqConst.ROUTING_ORDER}
  ))
  public void recceiver(OrderMqVo orderMqVo, Message message, Channel channel){
    if (orderMqVo.getAvailableNumber()!=null){
      Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
      schedule.setReservedNumber(orderMqVo.getReservedNumber());
      schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
      scheduleService.updateSchedule(schedule);
    }else {
      Schedule schedule = scheduleService.getById(orderMqVo.getScheduleId());
      int availableNumber = schedule.getAvailableNumber().intValue()+ 1;
      schedule.setAvailableNumber(availableNumber);
      scheduleService.updateSchedule(schedule);
    }

    //发送短信
    MsmVo msmVo = orderMqVo.getMsmVo();
    if(null != msmVo) {
      rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
    }
  }
}

